using MediatR;
using ProduceBasicData.Api.Application.Command.Material.MaterialType;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.MaterialType
{
    /// <summary>
    /// 物料类型查询处理类
    /// </summary>
    public class GetMaterialTypeHandler : IRequestHandler<GetMaterialTypeCommand, ApiResult<List<MaterialTypeDTO>>>
    {
        private readonly IBaseRespository<MaterialTypeDictionary> materialTypeRepository;

        public GetMaterialTypeHandler(IBaseRespository<MaterialTypeDictionary> materialTypeRepository)
        {
            this.materialTypeRepository = materialTypeRepository;
        }

        public Task<ApiResult<List<MaterialTypeDTO>>> Handle(GetMaterialTypeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<MaterialTypeDTO>>();

            try
            {
                // 获取物料类型数据
                var query = materialTypeRepository.GetAll().Where(x => !x.Isdel);

                // 如果只获取启用的类型
                if (request.OnlyEnabled)
                {
                    query = query.Where(x => x.IsEnabled);
                }

                // 映射到DTO
                var materialTypes = query
                    .OrderBy(x => x.SortOrder)
                    .Select(x => new MaterialTypeDTO
                    {
                        Id = x.Id,
                        TypeCode = x.TypeCode,
                        TypeName = x.TypeName,
                        TypeDesc = x.TypeDesc,
                        RequireDefaultCraft = x.RequireDefaultCraft,
                        SortOrder = x.SortOrder,
                        IsEnabled = x.IsEnabled
                    })
                    .ToList();

                result.Data = materialTypes;
                result.Code = ApiEnum.Success;
                result.Msg = "物料类型查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"物料类型查询异常：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
